package com.siam.package_rider.service_impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siam.package_common.constant.BusinessType;
import com.siam.package_common.constant.Quantity;
import com.siam.package_common.exception.StoneCustomerException;
import com.siam.package_common.util.*;
import com.siam.package_rider.cache.RiderSessionManager;
import com.siam.package_rider.controller.rider.WxLoginController;
import com.siam.package_rider.entity.*;
import com.siam.package_rider.enums.DeliveryOrderStatusEnum;
import com.siam.package_rider.mapper.TbRiderLevelMapper;
import com.siam.package_rider.mapper.TbRiderMapper;
import com.siam.package_rider.model.param.RiderWithdrawParam;
import com.siam.package_rider.model.param.TbRiderBillParam;
import com.siam.package_rider.model.param.TbRiderParam;
import com.siam.package_rider.model.result.TbRiderResult;
import com.siam.package_rider.service.TbDeliveryOrderService;
import com.siam.package_rider.service.TbRiderBillService;
import com.siam.package_rider.service.TbRiderService;
import com.siam.package_rider.service.TbRiderWithdrawRecordService;
import com.siam.package_rider.util.TokenUtil;
import com.siam.package_util.entity.Setting;
import com.siam.package_util.entity.SmsLog;
import com.siam.package_util.feign.SettingFeignApi;
import com.siam.package_util.feign.SmsLogFeignApi;
import com.siam.package_weixin_basic.config.WxSession;
import com.siam.package_weixin_basic.util.WxQrCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.siam.package_common.constant.RedisConstant.TRANSFER_ORDER_LIMIT_KEY;

/**
 * ---------------------------
 * 骑手表 (TbRiderServiceImpl)         
 * ---------------------------
 * 作者：  高品
 * 时间：  2025-03-29 18:55:18
 * ---------------------------
 */
@Slf4j
@Service
public class TbRiderServiceImpl extends ServiceImpl<TbRiderMapper, TbRider> implements TbRiderService {

	//注册方式 1=微信一键登录 2=手机验证码 3=邀请注册
	public static final int REGISTER_WAY_OF_WECHAT = 1;
	public static final int REGISTER_WAY_OF_MOBILECODE = 2;
	public static final int REGISTER_WAY_OF_INVITE = 3;

	public static final long DEFAULT_LEVEL_ID = 1L;

	public static final String DEFAULT_PASSWORD = "123456";

	@Autowired
	private TbRiderMapper riderMapper;

	@Autowired
	private RiderSessionManager riderSessionManager;

	@Autowired
	private OSSUtils ossUtils;

	@Autowired
	private SettingFeignApi settingFeignApi;

	@Autowired
	private TbRiderBillService riderBillService;

	@Autowired
	private TbRiderWithdrawRecordService riderWithdrawRecordService;

	@Autowired
	private WxQrCodeUtils wxQrCodeUtils;

	@Autowired
	private SmsLogFeignApi smsLogFeignApi;

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private TbDeliveryOrderService deliveryOrderService;

	@Autowired
	private TbRiderLevelMapper tbRiderLevelMapper;

	@Override
	public void insert(TbRiderParam param) {
		TbRider record = new TbRider();
		BeanUtils.copyProperties(param, record);
		record.setCreateTime(new Date());
        riderMapper.insert(record);
	}

	@Override
	public void delete(Long id) {
		riderMapper.deleteById(id);
	}

	@Override
	public void batchDelete(List<Long> idList) {
		riderMapper.deleteBatchIds(idList);
	}

	/**
	 * 修改个人资料(邮箱地址、性别、真实姓名)
	 * @param param
	 */
	@Override
	public void update(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());

		//目前只准修改邮箱地址、性别、真实姓名
		TbRider updateTbRider = new TbRider();
		updateTbRider.setId(loginTbRider.getId());
		updateTbRider.setEmail(param.getEmail());
		updateTbRider.setSex(param.getSex());
		updateTbRider.setRealName(param.getRealName());
		updateTbRider.setIsWork(param.getIsWork());
		updateTbRider.setIdCard(param.getIdCard());
		updateTbRider.setIdCardFrontImg(param.getIdCardFrontImg());
		updateTbRider.setIdCardBackImg(param.getIdCardBackImg());
		updateTbRider.setHeadImg(param.getHeadImg());
		updateTbRider.setAge(param.getAge());
		updateTbRider.setUrgentTel(param.getUrgentTel());
		updateTbRider.setUrgentUsername(param.getUrgentUsername());
		updateTbRider.setAddress(param.getAddress());
		updateTbRider.setAlipayAccount(param.getAlipayAccount());
		updateTbRider.setWechatAccount(param.getWechatAccount());
		updateTbRider.setOpeningBankName(param.getOpeningBankName());
		updateTbRider.setOpeningBankAddress(param.getOpeningBankAddress());
		updateTbRider.setBankCard(param.getBankCard());
		updateTbRider.setUpdateTime(new Date());
		riderMapper.updateById(updateTbRider);
	}

	@Override
	public Page<TbRider> page(TbRiderParam param) {
        Page<TbRider> page = riderMapper.page(new Page(param.getPageNo(), param.getPageSize()), param);
        return page;
	}

	@Override
	public TbRider findById(Long id) {
		return riderMapper.selectById(id);
	}

	@Override
	public void register(TbRiderParam param) {
		String systemMobileCode = (String) redisUtils.get("systemMobileCode");
		if(StringUtils.isNotBlank(systemMobileCode) && systemMobileCode.equals(param.getMobileCode())) {
			//万能验证码，放行
		}else{
			// 判断验证码是否匹配
			SmsLog smsLog = smsLogFeignApi.getLastLog(param.getMobile(), BusinessType.SMS_LOG_TYPE_REGISTER, 5).getData();
			if (smsLog==null || !smsLog.getVerifyCode().equals(param.getMobileCode())) {
				throw new StoneCustomerException("手机验证码错误");
			}
		}

		// 判断是否已经注册
		TbRider dbTbRider = riderMapper.selectByMobileOrIdCard(param.getMobile(), param.getIdCard());
		if (dbTbRider != null) {
			//用户已经注册，直接进行登录操作
			throw new StoneCustomerException("该用户已注册骑手");
		}

		String passwordSalt = CommonUtils.genSalt();
		String password = CommonUtils.genMd5Password(DEFAULT_PASSWORD, passwordSalt);

		// 添加rider记录
		TbRider insertTbRider = new TbRider();
		BeanUtils.copyProperties(param, insertTbRider);
		insertTbRider.setPassword(password);
		insertTbRider.setPasswordSalt(passwordSalt);
		insertTbRider.setLevelId(DEFAULT_LEVEL_ID);
//		insertTbRider.setAuditStatus(Quantity.INT_1);
		insertTbRider.setCreateTime(new Date());
		insertTbRider.setUpdateTime(new Date());
		riderMapper.insert(insertTbRider);
	}

	@Override
	public TbRiderResult fillAccountInfo(TbRiderParam param) {
		TbRiderResult riderResult = new TbRiderResult();
		log.debug("\n\n邀请者id : " + param.getInviterId());

		String systemMobileCode = (String) redisUtils.get("systemMobileCode");
		if(StringUtils.isNotBlank(systemMobileCode) && systemMobileCode.equals(param.getMobileCode())) {
			//万能验证码，放行
		}else{
			// 判断验证码是否匹配
			SmsLog smsLog = smsLogFeignApi.getLastLog(param.getMobile(), BusinessType.SMS_LOG_TYPE_REGISTER, 5).getData();
			if (smsLog==null || !smsLog.getVerifyCode().equals(param.getMobileCode())) {
				throw new StoneCustomerException("手机验证码错误");
			}
		}

		// 判断是否已经注册
		TbRider dbTbRiderByUsername = riderMapper.selectByUsername(param.getUsername());
		if (dbTbRiderByUsername != null) {
			throw new StoneCustomerException("该用户名已注册");
		}

		// 判断是否已经注册
		TbRider dbTbRider = riderMapper.selectByMobile(param.getMobile());
		if (dbTbRider != null) {
			//用户已经注册，直接进行登录操作
			String passwordSalt = CommonUtils.genSalt();
			String password = Base64Utils.decode(param.getPassword());
			password = CommonUtils.genMd5Password(password, passwordSalt);
			//更新用户登录信息
			TbRider updateTbRider = new TbRider();
			updateTbRider.setId(dbTbRider.getId());
			updateTbRider.setUsername(param.getUsername());
			updateTbRider.setPassword(password);
			updateTbRider.setPasswordSalt(passwordSalt);
			updateTbRider.setLoginCount(dbTbRider.getLoginCount() + 1);
			updateTbRider.setLastLoginTime(new Date());
			riderMapper.updateById(updateTbRider);
		}else{
			//自动实现注册功能
			String passwordSalt = CommonUtils.genSalt();
			String password = Base64Utils.decode(param.getPassword());
			password = CommonUtils.genMd5Password(password, passwordSalt);
			// 添加rider记录
			TbRider insertTbRider = new TbRider();
			BeanUtils.copyProperties(param, insertTbRider);
			insertTbRider.setPassword(password);
			insertTbRider.setPasswordSalt(passwordSalt);
			insertTbRider.setLevelId(DEFAULT_LEVEL_ID);
//			insertTbRider.setAuditStatus(Quantity.INT_1);
			insertTbRider.setCreateTime(new Date());
			insertTbRider.setUpdateTime(new Date());
			riderMapper.insert(insertTbRider);
		}

		// 重新查询
		dbTbRider = riderMapper.selectByMobile(param.getMobile());
		
		// 生成token
		String token = TokenUtil.generateToken(dbTbRider);

		//创建登录会话
		riderSessionManager.createSession(token, dbTbRider);

		//创建登录cookie
		TokenUtil.addLoginCookie(token);

		riderResult.setToken(token);
		return riderResult;
	}

	@Override
	public void fillVerificationInfo(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());
		// 更新rider记录
		TbRider rider = new TbRider();
		BeanUtils.copyProperties(param, rider);
		rider.setId(loginTbRider.getId());
		rider.setAuditStatus(Quantity.INT_1);
		rider.setUpdateTime(new Date());
		riderMapper.updateById(rider);
	}

	@Override
	public void registerWithFillVerificationInfo(TbRiderParam param) {
		String systemMobileCode = (String) redisUtils.get("systemMobileCode");
		if(StringUtils.isNotBlank(systemMobileCode) && systemMobileCode.equals(param.getMobileCode())) {
			//万能验证码，放行
		}else{
			// 判断验证码是否匹配
			SmsLog smsLog = smsLogFeignApi.getLastLog(param.getMobile(), BusinessType.SMS_LOG_TYPE_REGISTER, 5).getData();
			if (smsLog==null || !smsLog.getVerifyCode().equals(param.getMobileCode())) {
				throw new StoneCustomerException("手机验证码错误");
			}
		}

		// 判断是否已经注册
		TbRider dbTbRider = riderMapper.selectByMobileOrIdCard(param.getMobile(), param.getIdCard());
		if (dbTbRider != null && dbTbRider.getAuditStatus() != 3) {
			//用户已经注册，直接进行登录操作
			throw new StoneCustomerException("该用户已注册骑手");
		}else if (dbTbRider != null && dbTbRider.getAuditStatus() == 3) {
			// 审核失败，重新提交
			String passwordSalt = CommonUtils.genSalt();
			String password = Base64Utils.decode(param.getPassword());
			password = CommonUtils.genMd5Password(password, passwordSalt);
			TbRider tbRider = new TbRider();
			BeanUtils.copyProperties(param, tbRider);
			tbRider.setId(dbTbRider.getId());
			tbRider.setPassword(password);
			tbRider.setPasswordSalt(passwordSalt);
			tbRider.setAuditStatus(Quantity.INT_1);
			tbRider.setUpdateTime(new Date());
			riderMapper.updateById(tbRider);
			// todo - 记录到提交记录表
		}else{
			String passwordSalt = CommonUtils.genSalt();
			String password = Base64Utils.decode(param.getPassword());
			password = CommonUtils.genMd5Password(password, passwordSalt);

			// 添加rider记录
			TbRider insertTbRider = new TbRider();
			BeanUtils.copyProperties(param, insertTbRider);
			insertTbRider.setLevelId(DEFAULT_LEVEL_ID);
			insertTbRider.setPassword(password);
			insertTbRider.setPasswordSalt(passwordSalt);
//			insertTbRider.setAuditStatus(Quantity.INT_1);
			insertTbRider.setCreateTime(new Date());
			insertTbRider.setUpdateTime(new Date());
			riderMapper.insert(insertTbRider);
		}
	}

	@Override
	public TbRider selectByMobile(String mobile) {
		return riderMapper.selectByMobile(mobile);
	}

	@Override
	public TbRiderResult login(TbRiderParam param) {
		TbRider dbTbRider = riderMapper.selectByUsernameOrMobile(param.getUsername());
		if (dbTbRider == null) {
			throw new StoneCustomerException("该账号不存在");
		}

		// 判断密码是否匹配
		String password = Base64Utils.decode(param.getPassword());
		password = CommonUtils.genMd5Password(password, dbTbRider.getPasswordSalt());
		if (!password.equals(dbTbRider.getPassword())) {
			throw new StoneCustomerException("密码错误");
		}

		// 更新用户登录信息
		TbRider updateTbRider = new TbRider();
		updateTbRider.setId(dbTbRider.getId());
		updateTbRider.setLoginCount(dbTbRider.getLoginCount() + 1);
		updateTbRider.setLastLoginTime(new Date());
		riderMapper.updateById(updateTbRider);

		// 生成token
		String token = TokenUtil.generateToken(dbTbRider);

		//创建登录会话
		riderSessionManager.createSession(token, dbTbRider);

		//创建登录cookie
		TokenUtil.addLoginCookie(token);

		TbRiderResult riderResult = new TbRiderResult();
		riderResult.setToken(token);
		return riderResult;
	}

	@Override
	public TbRiderResult verificationLogin(TbRiderParam param) {
		TbRiderResult riderResult = new TbRiderResult();
		log.debug("\n\n邀请者id : " + param.getInviterId());

		String systemMobileCode = (String) redisUtils.get("systemMobileCode");
		if(StringUtils.isNotBlank(systemMobileCode) && systemMobileCode.equals(param.getMobileCode())) {
			//万能验证码，放行
		}else{
			// 判断验证码是否匹配
			SmsLog smsLog = smsLogFeignApi.getLastLog(param.getMobile(), BusinessType.SMS_LOG_TYPE_LOGIN, 5).getData();
			if (smsLog==null || !smsLog.getVerifyCode().equals(param.getMobileCode())) {
				throw new StoneCustomerException("手机验证码错误");
			}
		}

		//获取小程序openId
		WxSession wxSession = WxLoginController.getSessionKeyFromWxByCode(param.getCode());
//		if (wxSession.getOpenid() == null) {
//			throw new StoneCustomerException("用户唯一标识获取失败");
//		}
		log.debug("\n\n自动注册获取的openid：" + wxSession.getOpenid());

		// 判断是否已经注册
		TbRider dbTbRider = riderMapper.selectByMobile(param.getMobile());
		if (dbTbRider != null) {
			//用户已经注册，直接进行登录操作
			//更新用户登录信息
			TbRider updateTbRider = new TbRider();
			updateTbRider.setId(dbTbRider.getId());
			updateTbRider.setLoginCount(dbTbRider.getLoginCount() + 1);
			updateTbRider.setLastLoginTime(new Date());
			riderMapper.updateById(updateTbRider);
		}else{
			throw new StoneCustomerException("该账号不存在");
			//用户未操作，进行自动注册操作
//			dbTbRider = this.autoRegister(param, REGISTER_WAY_OF_MOBILECODE);
		}

		// 生成token
		String token = TokenUtil.generateToken(dbTbRider);

		//创建登录会话
		riderSessionManager.createSession(token, dbTbRider);

		//创建登录cookie
		TokenUtil.addLoginCookie(token);

		riderResult.setOpenId(wxSession.getOpenid());
		riderResult.setToken(token);
		return riderResult;
	}

	@Override
	public TbRiderResult wxLogin(TbRiderParam param) {
		TbRiderResult riderResult = new TbRiderResult();
		log.debug("\n\n邀请者id : " + param.getInviterId());

		// 判断是否已经注册
		TbRider dbTbRider = riderMapper.selectByMobile(param.getMobile());
		if (dbTbRider != null && dbTbRider.getAuditStatus() == 2) {
			//用户已经注册，直接进行登录操作
			//更新rider记录
			TbRider updateTbRider = new TbRider();
			updateTbRider.setId(dbTbRider.getId());
			updateTbRider.setLoginCount(dbTbRider.getLoginCount() + 1);
			updateTbRider.setIsBindWx(true);
			updateTbRider.setLastLoginTime(new Date());
			//如果用户之前未绑定微信，则需要更新用户的若干字段信息
			if(!dbTbRider.getIsBindWx()){
				updateTbRider.setUsername(param.getUsername());
				updateTbRider.setHeadImg(param.getHeadImg());
				updateTbRider.setSex(param.getSex());
				updateTbRider.setOpenId(param.getOpenId());
				updateTbRider.setIsBindWx(true);
			}
			riderMapper.updateById(updateTbRider);
		} else {
			throw new StoneCustomerException("该账号不存在");
			//用户未操作，进行自动注册操作
//			dbTbRider = this.autoRegister(param, REGISTER_WAY_OF_WECHAT);
		}

		// 生成token
		String token = TokenUtil.generateToken(dbTbRider);

		//创建登录会话
		riderSessionManager.createSession(token, dbTbRider);

		//创建登录cookie
		TokenUtil.addLoginCookie(token);

		riderResult.setToken(token);
		return riderResult;
	}

	/**
	 * 自动注册
	 */
	private TbRider autoRegister(TbRiderParam param, int registerWay){
		//获取积分设置
//		Setting setting = settingFeignApi.selectCurrent().getData();
//		BigDecimal registrationRewardPoints = setting.getRegistrationRewardPoints();
//		registrationRewardPoints = registrationRewardPoints == null ? BigDecimal.ZERO : registrationRewardPoints;

		//新用户注册赠送邀请新用户注册奖励金额
//		BigDecimal registrationRewardInviteRewardAmount = setting.getRegistrationRewardInviteRewardAmount();

		//默认密码为123456
		String passwordSalt = CommonUtils.genSalt();
		String password = "123456";
		password = CommonUtils.genMd5Password(password, passwordSalt);

		BigDecimal balance = BigDecimal.ZERO;

		// 添加rider记录
		TbRider insertTbRider = new TbRider();
		insertTbRider.setLevelId(DEFAULT_LEVEL_ID);
		insertTbRider.setUsername(param.getUsername());
		insertTbRider.setMobile(param.getMobile());
		insertTbRider.setPassword(password);
		insertTbRider.setPasswordSalt(passwordSalt);
		/*insertTbRider.setNickname(rider.getNickname());*/
		insertTbRider.setBalance(balance);
		insertTbRider.setLoginCount(Quantity.INT_1);
		insertTbRider.setInviteCode(null);
		insertTbRider.setIsDisabled(false);
		insertTbRider.setHeadImg(param.getHeadImg());
		insertTbRider.setRoles(null);
		insertTbRider.setSex(param.getSex());
		insertTbRider.setEmail(null);
		insertTbRider.setIsDisabled(false);
		insertTbRider.setIsDeleted(false);
		insertTbRider.setOpenId(param.getOpenId());
		insertTbRider.setIsBindWx(true);
		insertTbRider.setType(Quantity.INT_1);
		insertTbRider.setRegisterWay(Quantity.INT_1);
		insertTbRider.setCreateTime(new Date());
		insertTbRider.setUpdateTime(new Date());
		insertTbRider.setLastLoginTime(new Date());
		riderMapper.insert(insertTbRider);

		//从数据库中获取注册好的用户信息
		TbRider dbTbRider = riderMapper.selectByMobile(param.getMobile());

//		//生成邀请分享太阳码
//		String path = "data/images/invite_suncode/v1.0";
//		String fileName = "suncode_" + insertTbRider.getId() + ".png";
//		String savePath = path + "/" + fileName;
//		wxQrCodeUtils.generateSunCode("pages/login/choose/choose", "inviterId="+insertTbRider.getId(), savePath);
//		TbRider updateTbRider = new TbRider();
//		updateTbRider.setId(insertTbRider.getId());
//		updateTbRider.setInviteSuncode(savePath);
//		riderMapper.updateByPrimaryKeySelective(updateTbRider);

		//生成积分账单
//		if (registrationRewardPoints.compareTo(BigDecimal.ZERO) > 0) {
//			TbTbRiderBill riderBill = new TbTbRiderBill();
//			riderBill.setTbRiderId(insertTbRider.getId());
//			riderBill.setCoinType(TbTbRiderBill.COIN_TYPE_POINTS);
//			riderBill.setType(TbTbRiderBill.TYPE_REGISTER_REWARD_POINTS);
//			riderBill.setOperateType(TbTbRiderBill.OPERATE_TYPE_ADD);
//			riderBill.setNumber(registrationRewardPoints);
//			riderBill.setCreateTime(new Date());
//			riderBill.setMessage("新用户注册赠送积分");
//			riderBillService.insertSelective(riderBill);
//		}
//		if(registrationRewardInviteRewardAmount.compareTo(BigDecimal.ZERO) > 0){
//			//增加用户账单记录
//			TbTbRiderBill riderBill = new TbTbRiderBill();
//			riderBill.setTbRiderId(insertTbRider.getId());
//			riderBill.setType(TbTbRiderBill.TYPE_REGISTER_REWARD_INVITE_REWARD_AMOUNT);
//			riderBill.setOperateType(TbTbRiderBill.OPERATE_TYPE_ADD);
//			riderBill.setCoinType(TbTbRiderBill.COIN_TYPE_INVITE_REWARD_AMOUNT);
//			riderBill.setNumber(registrationRewardInviteRewardAmount);
//			riderBill.setMessage("新用户注册赠送奖励金额");
//			riderBill.setCreateTime(new Date());
//			riderBillService.insertSelective(riderBill);
//		}

		//赠送系统默认优惠券-新人3折卷
//		Coupons dbCoupons = couponsFeignApi.selectByPrimaryKey(BusinessType.NEW_PEOPLE_COUPONS_ID).getData();
//		if (dbCoupons == null) {
//			throw new StoneCustomerException("系统默认优惠券-新人3折卷不存在");
//		}
//		CouponsTbRiderRelation couponsTbRiderRelation = new CouponsTbRiderRelation();
//		couponsTbRiderRelation.setCouponsId(BusinessType.NEW_PEOPLE_COUPONS_ID);
//		couponsTbRiderRelation.setTbRiderId(insertTbRider.getId());
//		couponsTbRiderRelationFeignApi.insertSelective(couponsTbRiderRelation);

//		log.debug("邀请者id:" + param.getInviterId());
//		if (param.getInviterId() != null && !param.getInviterId().equals("") && !param.getInviterId().equals("undefined")) {
//			TbRider inviter = riderMapper.selectByPrimaryKey(Integer.valueOf(param.getInviterId()));
//			log.debug("通过id获取邀请者对象:"+inviter);
//			if (inviter != null && inviter.getId() != null) {
//				log.debug("邀请者id:"+inviter.getId());
//				log.debug("start-------创建用户邀请关系");
//				//创建用户邀请关系
//				TbRiderInviteRelation riderInviteRelation = new TbRiderInviteRelation();
//				riderInviteRelation.setInviterId(Integer.valueOf(param.getInviterId()));
//				riderInviteRelation.setTbRiderId(insertTbRider.getId());
//				riderInviteRelation.setCreateTime(new Date());
//				riderInviteRelationService.insertSelective(riderInviteRelation);
//				log.debug("end-------创建用户邀请关系");
//
//				log.debug("start-------发送邀请优惠卷");
//				//发送邀请卷
//				Coupons inviteCoupons = couponsFeignApi.selectByPrimaryKey(BusinessType.INVITE_NEW_PEOPLE_COUPONS_ID).getData();
//				if (inviteCoupons == null) {
//					throw new StoneCustomerException("系统默认优惠券-邀请新人卷不存在");
//				}
//				CouponsTbRiderRelation inviteCouponsTbRiderRelation = new CouponsTbRiderRelation();
//				inviteCouponsTbRiderRelation.setCouponsId(BusinessType.INVITE_NEW_PEOPLE_COUPONS_ID);
//				inviteCouponsTbRiderRelation.setTbRiderId(Integer.valueOf(param.getInviterId()));
//				couponsTbRiderRelationFeignApi.insertSelective(inviteCouponsTbRiderRelation);
//				log.debug("end-------发送邀请优惠卷");
//
//				//将注册方式改为邀请注册
//				updateTbRider = new TbRider();
//				updateTbRider.setId(insertTbRider.getId());
//				updateTbRider.setRegisterWay(TbRider.REGISTER_WAY_OF_INVITE);
//				riderMapper.updateByPrimaryKeySelective(updateTbRider);
//			}
//		}

		return dbTbRider;
	}

	@Override
	public TbRiderResult getLoginUserInfo(TbRiderParam param) {
		TbRiderResult riderResult = new TbRiderResult();
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());

		TbRider rider = riderMapper.selectById(loginTbRider.getId());

		TbRiderBillParam riderBillParam;

		List<Integer> balanceTypeList = new ArrayList<>();
		balanceTypeList.add(Quantity.INT_1);
		balanceTypeList.add(Quantity.INT_4);

		// 总收入
		riderBillParam = new TbRiderBillParam();
		riderBillParam.setRiderId(loginTbRider.getId());
		riderBillParam.setOperateType(Quantity.INT_1);
		riderBillParam.setCoinType(Quantity.INT_1);
		riderBillParam.setTypeList(balanceTypeList);
		BigDecimal totalIncome = riderBillService.selectSumNumber(riderBillParam, new Date("1900/1/1"), new Date("2900/1/1"));

		// 今日收入
		riderBillParam = new TbRiderBillParam();
		riderBillParam.setRiderId(loginTbRider.getId());
		riderBillParam.setOperateType(Quantity.INT_1);
		riderBillParam.setCoinType(Quantity.INT_1);
		riderBillParam.setTypeList(balanceTypeList);
		BigDecimal todayIncome = riderBillService.selectSumNumber(riderBillParam, DateUtilsExtend.getDayBegin(), DateUtilsExtend.getDayEnd());

		//昨日收益-邀请新用户注册奖励金额/佣金
//		riderBillParam = new TbTbRiderBillDto();
//		riderBillParam.setTbRiderId(loginTbRider.getId());
//		riderBillParam.setOperateType(TbTbRiderBill.OPERATE_TYPE_ADD);
//		riderBillParam.setCoinType(TbTbRiderBill.COIN_TYPE_INVITE_REWARD_AMOUNT);
//		BigDecimal daySumInviteRewardAmount = riderBillService.selectSumNumber(riderBillParam, DateUtilsExtend.getBeginDayOfYesterday(), DateUtilsExtend.getEndDayOfYesterDay());

		// 今日奖励
		balanceTypeList = new ArrayList<>();
		balanceTypeList.add(Quantity.INT_4);
		riderBillParam = new TbRiderBillParam();
		riderBillParam.setRiderId(loginTbRider.getId());
		riderBillParam.setOperateType(Quantity.INT_1);
		riderBillParam.setCoinType(Quantity.INT_1);
		riderBillParam.setTypeList(balanceTypeList);
		BigDecimal todayReward = riderBillService.selectSumNumber(riderBillParam, DateUtilsExtend.getDayBegin(), DateUtilsExtend.getDayEnd());

		// 今日支出
		riderBillParam = new TbRiderBillParam();
		riderBillParam.setRiderId(loginTbRider.getId());
		riderBillParam.setOperateType(Quantity.INT_2);
		riderBillParam.setCoinType(Quantity.INT_1);
		BigDecimal totalExpenses = riderBillService.selectSumNumber(riderBillParam, DateUtilsExtend.getDayBegin(), DateUtilsExtend.getDayEnd());

		// 今日单量
		LambdaQueryWrapper<TbDeliveryOrder> orderWrapper = new LambdaQueryWrapper();
		orderWrapper.eq(TbDeliveryOrder::getRiderId, loginTbRider.getId());
		orderWrapper.ge(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayBegin());
		orderWrapper.le(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayEnd());
		Integer totalOrderNum = deliveryOrderService.count(orderWrapper);

		// 今日完成订单
		orderWrapper = new LambdaQueryWrapper();
		orderWrapper.eq(TbDeliveryOrder::getRiderId, loginTbRider.getId());
		orderWrapper.eq(TbDeliveryOrder::getStatus, DeliveryOrderStatusEnum.COMPLETED);
		orderWrapper.ge(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayBegin());
		orderWrapper.le(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayEnd());
		Integer totalCompletedOrderNum = deliveryOrderService.count(orderWrapper);

		// 今日转单
		orderWrapper = new LambdaQueryWrapper();
		orderWrapper.eq(TbDeliveryOrder::getRiderId, loginTbRider.getId());
		orderWrapper.eq(TbDeliveryOrder::getIsTransfer, true);
		orderWrapper.ge(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayBegin());
		orderWrapper.le(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayEnd());
		Integer totalTransferOrderNum = deliveryOrderService.count(orderWrapper);

		// 今日已抢订单
		orderWrapper = new LambdaQueryWrapper();
		orderWrapper.eq(TbDeliveryOrder::getRiderId, loginTbRider.getId());
		orderWrapper.ge(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayBegin());
		orderWrapper.le(TbDeliveryOrder::getCreateTime, DateUtilsExtend.getDayEnd());
		Integer totalReceivedOrderNum = deliveryOrderService.count(orderWrapper);

		// 今日配送里程
		BigDecimal totalDeliveryDistance = BigDecimal.ZERO; //todo

		// 本月差评
		Integer currentMonthBadEvaluate = 0; //todo

		//处理返回结构
		BeanUtils.copyProperties(rider, riderResult);
		riderResult.setTotalIncome(totalIncome);
		riderResult.setTodayIncome(todayIncome);
		riderResult.setTodayReward(todayReward);
		riderResult.setTotalExpenses(totalExpenses);
		riderResult.setTotalOrderNum(totalOrderNum);
		riderResult.setTotalCompletedOrderNum(totalCompletedOrderNum);
		riderResult.setTotalTransferOrderNum(totalTransferOrderNum);
		riderResult.setTotalReceivedOrderNum(totalReceivedOrderNum);
		riderResult.setTotalDeliveryDistance(totalDeliveryDistance);
		riderResult.setCurrentMonthBadEvaluate(currentMonthBadEvaluate);

		TbRiderLevel tbRiderLevel = tbRiderLevelMapper.selectById(loginTbRider.getLevelId());
		if(ObjectUtils.isEmpty(tbRiderLevel)){
			throw new StoneCustomerException("骑手等级异常");
		}
		// 获取骑手的转单限制-单日
		String key = TRANSFER_ORDER_LIMIT_KEY + DateUtilsPlus.formatDate(new Date(), "YYYYMMdd") + loginTbRider.getId();
		if(!redisUtils.hasKey(key)){
			// key不存在，初始化
			redisUtils.set(key, Convert.toStr(tbRiderLevel.getTransferLimit()));
		}
		int todayAllowTransferOrderNum = Convert.toInt(redisUtils.get(key));
		// 当日可转单次数
		riderResult.setTodayAllowTransferOrderNum(todayAllowTransferOrderNum);

		return riderResult;
	}

	@Override
	public void removeBindingWx(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());
		// 更新rider记录
		TbRider rider = new TbRider();
		rider.setId(loginTbRider.getId());
		rider.setUpdateTime(new Date());
		rider.setIsBindWx(false);
		riderMapper.updateById(rider);
	}

	@Override
	public void uploadHeadImg(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());

		if (param.getFile() == null || param.getFile().getSize() == 0) {
			throw new StoneCustomerException("图片不能为空");
		}

		String headImg = ossUtils.uploadImage(param.getFile(), "rider", loginTbRider.getId());

		// 更新rider记录
		TbRider updateTbRider = new TbRider();
		updateTbRider.setId(loginTbRider.getId());
		updateTbRider.setHeadImg(headImg);
		updateTbRider.setUpdateTime(new Date());
		riderMapper.updateById(updateTbRider);
	}

	@Override
	public void updatePassword(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());

		// 判断原密码是否匹配
		TbRider rider = riderMapper.selectById(loginTbRider.getId());
		String oldPassword = Base64Utils.decode(param.getOldPassword());
		oldPassword = CommonUtils.genMd5Password(oldPassword, rider.getPasswordSalt());
		if (!oldPassword.equals(rider.getPassword())) {
			throw new StoneCustomerException("原密码错误");
		}

		// 对新密码进行盐值加密
		String newPassword = Base64Utils.decode(param.getNewPassword());
		newPassword = CommonUtils.genMd5Password(newPassword, rider.getPasswordSalt());
		if (newPassword.equals(rider.getPassword())) {
			throw new StoneCustomerException("新密码不能与原密码一样");
		}

		// 更新rider记录
		TbRider updateTbRider = new TbRider();
		updateTbRider.setId(loginTbRider.getId());
		updateTbRider.setPassword(newPassword);
		riderMapper.updateById(updateTbRider);
	}

	@Override
	public void logout(TbRiderParam param) {
		TbRider loginRider = riderSessionManager.getSession(TokenUtil.getToken());
		log.info("[骑手端登出]loginRider={},token={}", loginRider, TokenUtil.getToken());

//        //记录退出日志
//        LogManager.me().executeLog(LogTaskFactory.exitLog(LoginContextHolder.getContext().getUser().getId(), getIp()));

		//删除Auth相关cookies
		TokenUtil.deleteLoginCookie();

		//删除会话
		riderSessionManager.removeSession(TokenUtil.getToken());
	}

	@Override
	public void updateLastUseAddress(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());

		TbRider updateTbRider = new TbRider();
		updateTbRider.setId(loginTbRider.getId());
		updateTbRider.setLastUseTime(new Date());
		updateTbRider.setLastUseAddress(param.getLastUseAddress());
		updateTbRider.setLng(param.getLng());
		updateTbRider.setLat(param.getLat());
		riderMapper.updateById(updateTbRider);
	}

	@Override
	public void forgetPaymentPasswordStep1(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());
		TbRider dbTbRider = riderMapper.selectById(loginTbRider.getId());
		if(!dbTbRider.getMobile().equals(param.getMobile())){
			throw new StoneCustomerException("手机号错误");
		}

		if("123456".equals(param.getMobileCode())) {
			//万能验证码，放行
		}else{
			// 判断验证码是否匹配
			SmsLog smsLog = smsLogFeignApi.getLastLog(param.getMobile(), BusinessType.SMS_LOG_TYPE_FINDPWD, 5).getData();
			if (smsLog==null || !smsLog.getVerifyCode().equals(param.getMobileCode())) {
				throw new StoneCustomerException("手机验证码错误");
			}
		}

		//TODO-将验证码改为已验证
	}

	@Override
	public void forgetPaymentPasswordStep2(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());
		TbRider dbTbRider = riderMapper.selectById(loginTbRider.getId());

		//TODO-长时间未操作，请返回第一步重新操作

		//Base64解密
		String paymentPassword = Base64Utils.decode(param.getPaymentPassword());

		String paymentPasswordSalt = dbTbRider.getPaymentPasswordSalt() != null ? dbTbRider.getPaymentPasswordSalt() : CommonUtils.genSalt();
		if(org.apache.commons.lang3.StringUtils.isNotBlank(paymentPassword) && paymentPassword.length()!=6){
			throw new StoneCustomerException("密码长度错误");
		}
		paymentPassword = CommonUtils.genMd5Password(paymentPassword, paymentPasswordSalt);

		//修改用户支付密码
		TbRider updateTbRider = new TbRider();
		updateTbRider.setId(dbTbRider.getId());
		updateTbRider.setPaymentPassword(paymentPassword);
		updateTbRider.setPaymentPasswordSalt(paymentPasswordSalt);
		riderMapper.updateById(updateTbRider);
	}

	@Override
	public void verifyPaymentPassword(TbRiderParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());
		TbRider dbTbRider = riderMapper.selectById(loginTbRider.getId());

		//判断密码是否匹配
		String paymentPassword = Base64Utils.decode(param.getPaymentPassword());
		paymentPassword = CommonUtils.genMd5Password(paymentPassword, dbTbRider.getPaymentPasswordSalt());
		if(!paymentPassword.equals(dbTbRider.getPaymentPassword())){
			throw new StoneCustomerException("支付密码输入错误，请重新输入");
		}
	}

	@Override
	public void updateByAdmin(TbRiderParam param) {
		TbRider updateTbRider = new TbRider();
		BeanUtils.copyProperties(param, updateTbRider);
		riderMapper.updateById(updateTbRider);
	}

	@Override
	public void withdrawal(RiderWithdrawParam param) {
		//TODO-这里如果真实姓名未初始化时，还会输入一个真实姓名
		TbRider loginRider = riderSessionManager.getSession(TokenUtil.getToken());
		TbRider dbRider = riderMapper.selectById(loginRider.getId());

		if(StringUtils.isBlank(dbRider.getRealName())){
			throw new StoneCustomerException("您的真实姓名还未填写");
		}

		//判断密码是否匹配
		String paymentPassword = Base64Utils.decode(param.getPaymentPassword());
		paymentPassword = CommonUtils.genMd5Password(paymentPassword, dbRider.getPaymentPasswordSalt());
		if(!paymentPassword.equals(dbRider.getPaymentPassword())){
			throw new StoneCustomerException(500, "支付密码输入错误，请重新输入");
		}

		if(param.getWithdrawAmount().compareTo(BigDecimal.ZERO) <= 0){
			throw new StoneCustomerException("提现金额必须大于0");
		}

		Setting setting = settingFeignApi.selectCurrent().getData();
		if(dbRider.getBalance().compareTo(setting.getRiderWithdrawMeetAmount()) < 0){
			throw new StoneCustomerException("余额累计到(≥)" + setting.getRiderWithdrawMeetAmount() + "元才可以提现");
		}

		// 校验是否有在途提现记录
		LambdaQueryWrapper<TbRiderWithdrawRecord> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TbRiderWithdrawRecord::getRiderId, dbRider.getId());
		queryWrapper.in(TbRiderWithdrawRecord::getAuditStatus, TbRiderWithdrawRecord.AUDIT_STATUS_PROCESSING, TbRiderWithdrawRecord.AUDIT_STATUS_PAYMENT_PROCESSING);
		int count = riderWithdrawRecordService.count(queryWrapper);
		if(count > 0){
			throw new StoneCustomerException("您有提现记录正在审批，需要审批后才能再次提现！");
		}

		//自动计算平台手续费
		BigDecimal riderWithdrawFee = setting.getRiderWithdrawFee().divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
		BigDecimal platformFee = param.getWithdrawAmount().multiply(riderWithdrawFee).setScale(2, BigDecimal.ROUND_HALF_UP);
		BigDecimal totalAmount = param.getWithdrawAmount().add(platformFee).setScale(2, BigDecimal.ROUND_HALF_UP);

		BigDecimal actualAmount = param.getWithdrawAmount();
		if(totalAmount.compareTo(dbRider.getBalance()) > 0){
			actualAmount = param.getWithdrawAmount().subtract(platformFee).setScale(2, BigDecimal.ROUND_HALF_UP);
			totalAmount = param.getWithdrawAmount();
		}

		log.debug("\n\nriderWithdrawFee = " + riderWithdrawFee);
		log.debug("\n\nriderWithdrawRecord.getWithdrawAmount() = " + param.getWithdrawAmount());
		log.debug("\n\nplatformFee = " + platformFee);
		log.debug("\n\nactualAmount = " + actualAmount);
		log.debug("\n\ntotalAmount = " + totalAmount);
		//判断余额是否充足
		if(totalAmount.compareTo(dbRider.getBalance()) > 0){
			throw new StoneCustomerException("奖励金不足，请重新填写提现金额");
		}

		// 获取订单编号
		String orderNo = GenerateNo.RIDER_FLAG + GenerateNo.getOrderNo();

		// 添加提现记录
		TbRiderWithdrawRecord withdrawRecord = new TbRiderWithdrawRecord();
		BeanUtils.copyProperties(param, withdrawRecord);
		withdrawRecord.setRiderId(loginRider.getId());
		withdrawRecord.setOutTradeNo(orderNo);
		withdrawRecord.setPlatformFee(platformFee);
		withdrawRecord.setActualAmount(actualAmount);
		withdrawRecord.setCreateTime(new Date());
		withdrawRecord.setUpdateTime(new Date());
		riderWithdrawRecordService.save(withdrawRecord);

		//减少用户的邀请新用户注册奖励金额
		BigDecimal updateWithdrawableBalance = dbRider.getBalance().subtract(totalAmount).setScale(2, BigDecimal.ROUND_HALF_UP);

		TbRider updateRider = new TbRider();
		updateRider.setId(dbRider.getId());
		updateRider.setBalance(updateWithdrawableBalance);
		updateRider.setUpdateTime(new Date());
		this.updateById(updateRider);
		dbRider = this.getById(loginRider.getId());

		//TODO-增加用户账单记录
		TbRiderBill riderBill = new TbRiderBill();
		riderBill.setRiderId(dbRider.getId());
		riderBill.setType(Quantity.INT_2);
		riderBill.setOperateType(Quantity.INT_2);
		riderBill.setCoinType(Quantity.INT_1);
		riderBill.setNumber(actualAmount);
		riderBill.setServiceFee(platformFee);
		riderBill.setMessage("用户提现 -- 订单号" + orderNo);
		riderBill.setCreateTime(new Date());
		riderBillService.save(riderBill);
	}
}